import {Circle, Fill, Stroke, Style, Text} from "ol/style";

export default {
  data() {
    return {
      selected: null
    }
  },
  methods: {
    /**
     * 跳转到中心点
     * @param coordinate  中心点坐标[lng,lat]
     * @param zoom        缩放级别
     * @param options     其他参数
     */
    toMapCenter(coordinate, zoom, options) {
      this.map.getView().animate({
        center: coordinate, // 中心点
        zoom: zoom || 12, // 缩放级别
        duration: 500, // 缩放持续时间，默认不需要设置
        easing: (e) => {
          if (e === 1) {
            // 动画结束
            options && options.animateAfterFunc && options.animateAfterFunc(coordinate)
          }
          return e
        }
      })
    },
    /**
     * 跳转到中心点并还原到初始地图层级
     * @param coordinate [lng,lat] 中心点坐标
     */
    toMapZoomCenter(coordinate) {
      let params = JSON.parse(this.gisIns.option.params)
      let center = params.center
      this.map.getView().animate({
        center: coordinate || center,
        zoom: params.zoom, // 默认缩放级别
        duration: 500 // 缩放持续时间，默认不需要设置
      })
    },
    /**
     *
     */
    toMapViewExtent(coordinates) {
      this.gisIns.viewExtent(coordinates, {
        duration: 300,
        padding: [50, 50, 50, 50],
      })
    },
    /**
     * 设置图层可见
     * @param layerId
     * @param visible 是否可见
     */
    setHeatMapVisible(layerId, visible) {
      let mapLayer = this.gisIns.getLayer(layerId)
      if (mapLayer) {
        mapLayer.setVisible(visible);
        mapLayer.set('hidden', !visible)
      }
    },
    // 聚合图层
    createMapAggregation(Features, option) {
      let {layerId = 'clusterSourceLayer', targetId = 'markerLayer'} = option
      let clusterLayer = this.gisIns.getLayer(layerId)
      if (!clusterLayer) {
        clusterLayer = this.gisIns.createClusterVector({
          zIndex: 6,
          style: function (feature, resolution) {
            var size = feature.get('features').length
            return new Style({
              image: new Circle({
                radius: 20,
                stroke: new Stroke({
                  color: 'rgba(45, 207, 251, .7)'
                }),
                fill: new Fill({
                  color: 'rgba(45, 207, 251, .7)'
                })
              }),
              text: new Text({
                text: size.toString(),
                font: '12px PingFangSC-Regular, PingFang SC',
                fill: new Fill({
                  color: '#FFFFFF'
                })
              })
            })
          }
        }, layerId)
      }

      if (!clusterLayer) return
      clusterLayer.setVisible(true)
      //聚合图层的source 需要多取一层
      let source = clusterLayer.getSource().getSource()
      source.clear()
      source.addFeatures(Features)
      let view = this.map.getView()
      let targetLayer = this.gisIns.getLayer(targetId)
      // 监听地图分辨率改变事件
      view.on('change:resolution', (event) => {
        if (clusterLayer.get('hidden') !== undefined && clusterLayer.get('hidden')) {
          return;
        }
        if (view.getZoom() > 17) {
          clusterLayer.setVisible(false)
          targetLayer && targetLayer.setVisible(true)
        } else {
          clusterLayer.setVisible(true)
          targetLayer && targetLayer.setVisible(false)
        }
      })

      this.map.on('click', (e) => {
        //如果是聚合图层点击事件
        // 获取点击位置的Feature
        clusterLayer.getFeatures(e.pixel).then((clickedFeatures) => {
          if (clickedFeatures.length) {
            // Get clustered Coordinates
            const features = clickedFeatures[0].get('features');

            const extent = this.gisIns.boundingExtent(
              features.map((r) => r.getGeometry().getCoordinates())
            )
            // eslint-disable-next-line no-undef
            let [width, height] = map.getSize()
            width = Math.ceil(width)
            height = Math.ceil(height / 5)
            // 定位到点击位置
            // eslint-disable-next-line no-undef
            map.getView().fit(extent, {
              duration: 500,
              padding: [height, width, height, width + 500]
            })
          }
        })
      })

      // this.map.on(['pointermove'], (evt) => {
      //   if (evt.dragging) {
      //     return
      //   }
      //   const feature = this.map.forEachFeatureAtPixel(evt.pixel, function (feature) {
      //     return feature
      //   })
      //   if (feature) {
      //     this.map.getTarget().style.cursor = 'pointer'
      //   } else {
      //     this.map.getTarget().style.cursor = ''
      //   }
      // })
    },
    /**
     * 地图复位 （居中，zoom等）
     * @returns {Promise<unknown>}
     */
    resetMapView() {
      return new Promise(resolve => {
        if (!this.gisIns || !this.map) {
          return;
        }
        let mapParams = JSON.parse(this.gisIns.option.params)
        this.map.getView().animate({
          center: this.gisIns.transform(mapParams.center[0], mapParams.center[1]),
          zoom: mapParams.zoom, // 默认缩放级别
          duration: 300 // 缩放持续时间，默认不需要设置
        })
        setTimeout(() => {
          resolve(true)
        }, 300)
      });
    },
    // 计算中心点
    getPointsCenter(coordinates) {
      //坐标点个数
      let point_num = coordinates.length;
      let X = 0, Y = 0, Z = 0;
      coordinates.forEach((item, index) => {
        let lat, lng, x, y, z;
        lng = parseFloat(item[0]) * Math.PI / 180;
        lat = parseFloat(item[1]) * Math.PI / 180;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      })

      X = X / point_num;
      Y = Y / point_num;
      Z = Z / point_num;
      let tmp_lng = Math.atan2(Y, X);
      let tmp_lat = Math.atan2(Z, Math.sqrt(X * X + Y * Y));
      return [tmp_lng * 180 / Math.PI, tmp_lat * 180 / Math.PI];
    },
  }
}
